import {asyncRoutes, constantRoutes} from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param myMenuPrivileges
 * @param route
 */
function hasPermission(myMenuPrivileges, route) {
  if (route.meta && route.meta.pkey) {
    console.log("菜单权限>" + route.meta.title + ">" + route.meta.pkey)
    if (myMenuPrivileges && myMenuPrivileges[0] === "all") {
      return true;
    }
    return myMenuPrivileges.some(privilege => route.meta.pkey === privilege)
  } else {
    console.log("菜单没有配置权限>" + route.name)
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param myMenuPrivileges
 */
export function filterAsyncRoutes(routes, myMenuPrivileges) {
  const res = []

  routes.forEach(route => {
    const tmp = {...route}
    if (hasPermission(myMenuPrivileges, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, myMenuPrivileges)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  permissionRoutes: [],
  myDynamicRoutes: []
}

const mutations = {
  SET_PERMISSION_ROUTES: (state, permissionRoutes) => {
    state.myDynamicRoutes = permissionRoutes
    state.permissionRoutes = constantRoutes.concat(permissionRoutes)
  }
}

const actions = {
  generateMyRoutes({commit}, myMenuPrivileges) {
    return new Promise(resolve => {
      const permissionRoutes = filterAsyncRoutes(asyncRoutes, myMenuPrivileges)
      commit('SET_PERMISSION_ROUTES', permissionRoutes)
      resolve(permissionRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
